//
//  LoginViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/28.
//

import UIKit
import PKHUD

// 登陆成功代理
protocol LoginViewControllerDelegate {
    func loginSuccess(user: UserModel)
}

class LoginViewController: UIViewController {

    @IBOutlet weak var userNameTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    
    var delegate:LoginViewControllerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if #available(iOS 13.0, *) {
            view.backgroundColor = Colors.backgroundColor
        }
        
        setupNavigationBar()
    }

    // 设置关闭按钮
    func setupNavigationBar(){
        
        let closeBtn = UIButton(type: .custom)
        closeBtn.setTitle("关闭", for: .normal)
        closeBtn.setTitleColor(Colors.BLUE_COLOR, for: .normal)
        closeBtn.addTarget(self, action: #selector(closeFunc), for: .touchUpInside)
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: closeBtn)
    }
    
    @objc func closeFunc(){
        self.dismiss(animated: true, completion: nil)
    }
    
    @IBAction func loginButtonClick(_ sender: Any) {
        
        guard let userName = userNameTextField.text,let pwd = passwordTextField.text else {
            HUD.flash(.label("邮箱或密码不能为空"), delay: 1.0)
            return
        }
        if userName.trimmingCharacters(in: .whitespaces).isEmpty
            || pwd.trimmingCharacters(in: .whitespaces).isEmpty {
            
            HUD.flash(.label("邮箱或密码不能为空"), delay: 1.0)
            return
        }
        
        let url = URLs.AOUTHURL
        /*
         v5的授权登陆参数总包错 采用v3 的
         "client_id":URLs.CLIENT_ID,
         "client_secret":URLs.CLIENT_SECRET,
         "scope":"user_info projects pull_requests issues notes keys hook groups gists enterprises"
         */
        let parmeters = ["email":userName,
                         "password":pwd,
                        ]
        
        HUD.show(.progress)
        // 异步加载
        DispatchQueue.global().async {
            
            let headers = ["Content-Type":"application/json"]
            let user:Result<UserModel> = NetWorkTool.shared.getRequest(url: url,method: .post, parameters: parmeters,headers: headers)
            DispatchQueue.main.async {
                HUD.hide()
                if user.code == 0 {
                    
                    if user.data?.id == nil {
                        HUD.flash(.label("登陆失败"), delay: 2.0)
                    }else {
                        self.loginSuccess(user: user.data!)
                    }
                    
                }else {
                    HUD.flash(.label(user.message), delay: 2.0)
                }
            }
        }
    }
    
    /// 登陆成功处理
    /// 保存token到用户偏好设置
    /// 利用代理传递用户数据给个人界面
    func loginSuccess(user: UserModel){
        
        UserDefaultTools.setUser(user: user)
        UserDefaultTools.setToken(token: user.private_token!)
        delegate?.loginSuccess(user: user)
        self.dismiss(animated: true, completion: nil)
    }

}
